# 引入Django框架http模块中的 HttpResponse函数
from django.shortcuts import redirect, render
from django.http import HttpResponse, response
from django.conf.urls import url
from django.shortcuts import HttpResponse as httpRes
from .models import Users, Goods, goodsCars
from django.core.paginator import Paginator
from .util import page_paginator


# 显示用户购物车
def show_car(request):
    if request.method == "GET":
        if request.session.get('user', None):
            uid = request.session['user']['uid']
            goods_car = goodsCars.objects.filter(uid=uid)
            goods = []
            for item in goods_car:
                # good = Goods.objects.filter(gid=item.gid).first()
                good = item.good
                good.chice_count = item.chice_count
                good.all_price = item.chice_count * good.price
                goods.append(good)
            return render(request, 'goodsCar.html', context={"goods": goods})
        else:
            return redirect('/login/')


# 商品详情页
def commodity(request):
    context = {}
    # 显示所有数据
    if request.method == "GET":
        good_id = request.GET.get('gid')
        good = Goods.objects.filter(gid=good_id).first()
        context['good'] = good

    # 添加购物车
    if request.method == "POST":
        if request.session.get('user', None):
            gid = request.POST.get('gid')
            uid = request.session['user']['uid']
            if gid:

                good_is = Goods.objects.filter(gid=gid).first()
                siTure = goodsCars.objects.filter(good=good_is, uid=uid)
                # 存在添加数量
                if siTure.first():
                    siTure.update(chice_count=(siTure.first().chice_count + 1))
                # 不存在新建
                else:
                    # 添加id
                    # good_save = goodsCars(gid=gid, chice_count=1, uid=uid)
                    # 一对多，外键
                    good_save = goodsCars(good=good_is, chice_count=1, uid=uid)
                    good_save.save()
            good = Goods.objects.filter(gid=gid).first()
        else:
            return redirect('/login/')
        context['good'] = good
    return render(request, 'commodity.html', context)


# 多级导航览
def nav(request):
    nav = [{"chice": "学院管理",
            "select1": [{"chice": "理工农学院",
                         "select2": [{"name": "计算机科学与技术"}, {"name": "园林设计"}, {"name": "土木工程"},
                                     {"name": "经济管理"}]},
                        {"chice": "医学院",
                         "select2": [{"name": "护理"}, {"name": "内外人体学"}, {"name": "人体组织"}, {"name": "骨学"}]},
                        {"chice": "文艺法学院",
                         "select2": [{"name": "传统舞蹈学"}, {"name": "司法学"}, {"name": "流行音乐学"}]}]},

           {"chice": "师资团队", "select1": [{"chice": "衣服"}, {"chice": "裤子"}, {"chice": "服务器"}]},
           {"chice": "科学研究", "select1": [{"chice": "客户数据"}, {"chice": "用户数据"}, {"chice": "账单"}]},
           {"chice": "招生就业", "select1": [{"chice": "客户图览"}, {"chice": "用户图览"}]},
           ]
    return render(request, "nav.html", {"nav": nav})


# 设置处理函数
def getRes(request):
    if request.method == "GET":
        str = "<h1 align='center' style='font-size:30px;" \
              "color:red;font-weight: bold;'>你好</h1>"
        return HttpResponse(str)


# 响应html
def index(request):
    name = request.session.get('user', '')
    if name:
        name = name['name']
    students = [{"name": "小明", "score": 91},
                {"name": "张三", "score": 81},
                {"name": "李四", "score": 61},
                {"name": "王五", "score": 71},
                {"name": "麻子", "score": 51},
                {"name": "二毛", "score": 66},
                ]
    word = request.GET.get('word', 1)
    page = int(request.GET.get('page', 1))
    if word != 1:
        goods = Goods.objects.filter(name__contains=word).order_by('gid')[5 * (page - 1):5 * page]
        count = Goods.objects.filter(name__contains=word).order_by('gid').count()
    else:
        goods = Goods.objects.all().order_by('gid')[5 * (page - 1):5 * page]
        count = Goods.objects.all().order_by('gid').count()
    context = {}
    context['name'] = name
    context['students'] = students
    context['page'] = page
    context['count'] = count
    context['goods'] = goods
    context['page_data'] = page_paginator(5, page, count)
    context['page_show'] = [i if i > 0 else 1 for i in range((context['page_data']['has_next_num']) - 2,
                                                             (context['page_data']['has_next_num']) + 1)]
    return render(request, 'index.html', context)


# 登录页面
def login(request):
    context = {}
    if request.method == "GET":
        return render(request, "login.html")
    if request.method == "POST":
        name = request.POST.get('name')
        password = request.POST.get('password')
        if all([name, password]):
            user = Users.objects.filter(username=name).first()
            if not user:
                context['message'] = "用户不存在"
                return redirect('/register/')
            else:
                if name == user.username and password == user.passwd:
                    request.session['user'] = {'name': user.username, 'uid': user.id}
                    request.session.set_expiry(0)
                    return redirect('/index/')
                context['message'] = "密码错误"
        else:
            context['message'] = "参数不全"
        return render(request, "login.html", context)


# 退出登录
def logout(request):
    # 只删除某个对象
    # request.session.pop('uid')
    # del request.session['uid']
    # request.session.clear()

    # 删除对应的表的数据
    # request.session.delete(request.session.session_key)
    request.session.flush()
    return redirect('/index/')


# 测试注册
def register(request):
    context = {}
    if request.method == "GET":
        return render(request, "register.html")
    if request.method == "POST":
        name = request.POST.get('name')
        password = request.POST.get('password')
        if all([name, password]):
            if Users.objects.filter(username=name).first():
                context['message'] = "用户已注册"
            else:
                user = Users(username=name, passwd=password)
                if not user.save():
                    context['message'] = "注册成功"
                    return redirect('/login/')
                context['message'] = '注册失败'
        else:
            context['message'] = '注册失败'
        return render(request, "register.html", context)
